package com.freeter.modules.controller;

import com.freeter.modules.gjs.entity.MstrDivision;
import com.freeter.modules.gjs.service.MstrDivisionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/mstr-division")
@CrossOrigin(origins = "*")
public class MstrDivisionController {

    @Autowired
    private MstrDivisionService mstrDivisionService;

    @GetMapping
    public ResponseEntity<List<MstrDivision>> getAllDivisions() {
        List<MstrDivision> divisions = mstrDivisionService.getAllDivisions();
        return ResponseEntity.ok(divisions);
    }

    @GetMapping("/{id}")
    public ResponseEntity<MstrDivision> getDivisionById(@PathVariable Long id) {
        MstrDivision division = mstrDivisionService.getDivisionById(id);
        if (division != null) {
            return ResponseEntity.ok(division);
        }
        return ResponseEntity.notFound().build();
    }

    @GetMapping("/code/{divisionCode}")
    public ResponseEntity<MstrDivision> getDivisionByCode(@PathVariable String divisionCode) {
        MstrDivision division = mstrDivisionService.getDivisionByCode(divisionCode);
        if (division != null) {
            return ResponseEntity.ok(division);
        }
        return ResponseEntity.notFound().build();
    }

    @PostMapping
    public ResponseEntity<MstrDivision> createDivision(@RequestBody MstrDivision division) {
        MstrDivision createdDivision = mstrDivisionService.createDivision(division);
        return ResponseEntity.ok(createdDivision);
    }

    @PutMapping("/{id}")
    public ResponseEntity<MstrDivision> updateDivision(@PathVariable Long id, @RequestBody MstrDivision division) {
        try {
            MstrDivision updatedDivision = mstrDivisionService.updateDivision(id, division);
            return ResponseEntity.ok(updatedDivision);
        } catch (RuntimeException e) {
            return ResponseEntity.notFound().build();
        }
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteDivision(@PathVariable Long id) {
        mstrDivisionService.deleteDivision(id);
        return ResponseEntity.ok().build();
    }

    @DeleteMapping("/code/{divisionCode}")
    public ResponseEntity<Void> deleteDivisionByCode(@PathVariable String divisionCode) {
        mstrDivisionService.deleteDivisionByCode(divisionCode);
        return ResponseEntity.ok().build();
    }

    @GetMapping("/status/{status}")
    public ResponseEntity<List<MstrDivision>> getDivisionsByStatus(@PathVariable String status) {
        List<MstrDivision> divisions = mstrDivisionService.getDivisionsByStatus(status);
        return ResponseEntity.ok(divisions);
    }
}